package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.goods.pojo.Goods;
import com.itheima.goods.vo.GoodsInfo;
import com.itheima.search.mapper.GoodsMapper;
import com.itheima.search.service.GoodService;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;


@Service
public class GoodServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodService {

    private final String GOODS_SYNC_DATABASE = "goodsinfo";

    @Qualifier("createRestHighLevelClient")
    @Autowired
    private RestHighLevelClient client;

    @Override
    public void goodsSync() {
        List<Goods> goods = this.baseMapper.selectList(null);

        //es数据库是否存在,存在则删除
        if (isExist()){
            deleteESDataBase();
        }
        //创建es索引库
        createESDataBase();

        //数据导入索引库中
        if(goods!=null && !goods.isEmpty()){
            importDataBase(goods);
        }
    }

    private void importDataBase(List<Goods> goods) {
        BulkRequest bulkRequest = new BulkRequest(GOODS_SYNC_DATABASE);
        goods.stream()
                .map(this::convertGoodsToGoodsInfo)
                .map(goodInfo->{
                    IndexRequest indexRequest = new IndexRequest();
                    indexRequest.id(goodInfo.getId()+"");
                    indexRequest.source(JSON.toJSONString(goodInfo),XContentType.JSON);
                    return indexRequest;
                })
                .forEach(bulkRequest::add);
        try {
            client.bulk(bulkRequest,RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("批量添加索引失败");
        }
    }

    private GoodsInfo convertGoodsToGoodsInfo(Goods goods) {
        String goodsStr = JSON.toJSONString(goods);
        GoodsInfo goodsInfo = JSON.parseObject(goodsStr, GoodsInfo.class); //名称相同的属性会自动封装;
        //组装品牌及名称
        goodsInfo.setBrandName(goods.getBrand());
        //组装分类数据
        goodsInfo.setCategoryName(goods.getCategory());
        //组装
        String spec = goods.getSpec();
        Map sepcMap = JSON.parseObject(spec, Map.class);
        goodsInfo.setSpecMap(sepcMap);
        goodsInfo.setCreateTime(goods.getCreatetime());
        goodsInfo.setUpdateTime(goods.getUpdatetime());
        return goodsInfo;
    }


    private boolean isExist(){
        GetIndexRequest request = new GetIndexRequest(GOODS_SYNC_DATABASE);
        try {
            return client.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private void createESDataBase(){
        CreateIndexRequest request = new CreateIndexRequest(GOODS_SYNC_DATABASE);
        request.mapping("{" +
                "\"properties\": {" +
                "\"id\": {" +
                "\"type\": \"integer\"" +
                "}," +
                "\"image\": {" +
                "\"index\": false," +
                "\"type\": \"keyword\"" +
                "}," +
                "\"brandId\": {" +
                "\"type\": \"integer\"" +
                "}," +
                "\"categoryId\": {" +
                "\"type\": \"integer\"" +
                "}," +
                "\"brandName\": {" +
                "\"type\": \"keyword\"" +
                "}," +
                "\"categoryName\": {" +
                "\"type\": \"keyword\"" +
                "}," +
                "\"num\": {" +
                "\"type\": \"integer\"" +
                "}," +
                "\"specMap\": {" +
                "\"type\": \"object\"" +
                "}," +
                "\"updateTime\": {" +
                "\"type\": \"date\"" +
                "}," +
                "\"spec\": {" +
                "\"type\": \"keyword\"" +
                "}," +
                "\"createTime\": {" +
                "\"type\": \"date\"" +
                "}," +
                "\"price\": {" +
                "\"type\": \"integer\"" +
                "}," +
                "\"name\": {" +
                "\"analyzer\": \"ik_max_word\"," +
                "\"type\": \"text\"" +
                "}," +
                "\"status\": {" +
                "\"type\": \"keyword\"" +
                "}" +
                "}" +
                "}",XContentType.JSON);
        try {
            client.indices().create(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void deleteESDataBase(){
        DeleteIndexRequest request = new DeleteIndexRequest(GOODS_SYNC_DATABASE);
        try {
            client.indices().delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
